import db from '../../core/db';
import http from '@ohos.net.http';
import utils from '../../core/utils';
import logger from '../../core/logger';
import current from '../../core/current';
import { apiProvider } from './apiProvider';
import axios, { AxiosError } from '@ohos/axios';

export abstract class clientBase {
  constructor() {
    axios.defaults.headers.common['x-bili-aurora-zone'] = 'sh001';
    axios.defaults.headers.common['x-bili-aurora-eid'] = 'UlMFQVcABlAH';
    axios.defaults.headers.common['origin'] = 'https://manga.bilibili.com';
    axios.defaults.headers.common['referer'] = 'https://manga.bilibili.com';
    axios.defaults.headers.post['content-type'] = 'application/x-www-form-urlencoded';
    axios.defaults.headers.common['user-agent'] = 'Mozilla/5.0 BiliDroid/5.44.2 (bbcallen@gmail.com)';
  }

  public async updateCookie() {
    try {
      let cookie = current.instance.cookie;
      if (utils.isEmpty(cookie)) {
        let value = await db.instance.query('login_cookie');
        cookie = value?.toString();
      }
      axios.defaults.headers.common['cookie'] = cookie;
    } catch (err) {
      logger.error(err);
    }
  }

  protected isSuccess(data: any): boolean {
    if (data != null && typeof data != 'undefined')
      if (data.code == '0')
        return true;
    return false;
  }

  protected repMessage(data: any): string {
    try {
      if (data != null && typeof data != 'undefined') {
        if (typeof data.msg == 'string')
          return data.msg;
        if (typeof data.message == 'string')
          return data.msg;
      }
    } catch (err) {
      logger.error(err);
    }
    return '';
  }

  protected errMessage(err: AxiosError): string {
    try {
      if (err != null && typeof err != 'undefined') {
        if (typeof err.response.data !== 'undefined')
          return err.response.data.toString();
      }
    } catch (err) {
      logger.error(err);
    }
    return err.name;
  }

  protected createGetParam(url: string, login: boolean = false): Promise<string> {
    return new Promise((resolve) => {
      try {
        let key = login ? apiProvider.loginKey : apiProvider.androidKey;
        let timestamp = (new Date()).valueOf();
        url += (url.indexOf('?') > -1) ? '&' : '?';
        url += `access_key=${current.instance.accessKey}&mid=${current.instance.mid}&appkey=${key.appKey}&platform=android&device=android&actionKey=appkey&build=5520400&mobi_app=android_comic&ts=${timestamp}`;
        url += apiProvider.getSign(url, key);
      } catch (err) {
        logger.error(err);
      }
      resolve(url);
    });
  }

  protected createPostParam(postContent: string = '', login: boolean = false): Promise<string> {
    return new Promise((resolve) => {
      try {
        let accessKey = current.instance.accessKey;
        let key = login ? apiProvider.loginKey : apiProvider.androidKey;
        let timestamp = (new Date()).valueOf();
        if (!login) {
          if (postContent != '')
            postContent += '&';
          postContent += `access_key=${accessKey}&appkey=${key.appKey}&mobi_app=android_comic&device=android&version=3.0.0&actionKey=appkey&platform=android&ts=${timestamp}`;
        } else {
          if (postContent == '')
            postContent += '&';
          postContent += `access_key=&appkey=${key.appKey}&platform=android&mobi_app=android&device=phone&ts=${timestamp}&build=7270300`;
        }
        postContent += apiProvider.getSign(postContent, key);
        resolve(postContent);
      } catch (err) {
        logger.error(err);
        resolve('');
      }
    });
  }

  protected postHttpData(url: string, postContent?: string): Promise<any> {
    return new Promise((resolve) => {
      try {
        this.createPostParam(postContent, false).then((paras) => {
          let httpRequest = http.createHttp();
          httpRequest.request(url,
            {
              method: http.RequestMethod.POST,
              header: {
                'x-bili-aurora-zone': 'sh001',
                'x-bili-aurora-eid': 'UlMFQVcABlAH',
                'origin': 'https://www.bilibili.com',
                'referer': 'https://www.bilibili.com',
                'content-type': 'application/x-www-form-urlencoded',
                'user-agent': 'Mozilla/5.0 BiliDroid/5.44.2 (bbcallen@gmail.com)'
              },
              extraData: paras,
              connectTimeout: 60000,
              readTimeout: 60000,
            }, (err, data) => {
              try {
                if (!err) {
                  if (data.responseCode == http.ResponseCode.OK && data.result != null && typeof data.result != 'undefined') {
                    let json = JSON.parse(data.result.toString());
                    resolve(json);
                  } else {
                    logger.info('fail:' + JSON.stringify(data), true);
                    resolve(null);
                  }
                } else {
                  logger.info('error:' + JSON.stringify(err), true);
                  resolve(null);
                }
              } catch (e) {
                logger.error(e, true);
                resolve(null);
              }
              httpRequest.destroy();
            });
        });
      } catch (err) {
        logger.error(err);
        resolve(null);
      }
    });
  }
}